﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Collections;
namespace Littlebeer.MDM.MSO
{
   public class KeyMatcher
    {
       public void MatchKeys(DataTable MainData,List<Littlebeer.Common.FieldMapping.FieldPairModel> mapping,string connectionstring, List<Littlebeer.MDM.MSO.EntityMatchErroModel> errolist)
       {          
           new Littlebeer.MDM.MSO.TableManager(connectionstring).AddPrimaryKey(MainData, "IID");
           Hashtable EntityAndGroup = new Littlebeer.MDM.MSO.EntityManager(connectionstring).GetUseFullEntityIndentityGroup(mapping);

           foreach (DictionaryEntry item in EntityAndGroup)
           {
               //逐个实体
               EntityModel entity = new EntityManager(connectionstring).Get(item.Key.ToString());
               string targetkey = new Littlebeer.MDM.MSO.TableManager(connectionstring).GetIdendtityColumn(entity.EntityName);
               new Littlebeer.MDM.MSO.TableManager(connectionstring).AddColumn(MainData, targetkey);
               //逐个规则
               foreach (EntityIndentityGroup group in item.Value as List<EntityIndentityGroup>)
               {
                   DataTable dt_TargetMatch = GetEntityTargetRuleTable(MainData, entity, group, connectionstring);
                   
                   
                   List<string> sourcegroup = new List<string>();
                   foreach (string str in group)
                   {
                       sourcegroup.Add(new Littlebeer.Common.FieldMapping.MappingManager().GetSourceFieldName(str, mapping));
                   }

                   new Littlebeer.MDM.MSO.TableManager(connectionstring).AddColumn(MainData, "MatchValue", sourcegroup);

                   var query = from a in MainData.AsEnumerable()
                               join b in dt_TargetMatch.AsEnumerable() on a.Field<string>("MatchValue") equals b.Field<string>("MatchValue")
                               where b.Field<int>("IID") != null && a.Field<string>("MatchValue") != null && b.Field<string>("MatchValue") != null
                               select  new { ID = a.Field<string>(MainData.PrimaryKey[0].ColumnName), IID = b.Field<int>("IID"), Key = b.Field<string>("MatchValue") };
                   var count = query.Count();
                   foreach (var mymatch in query)
                   {
                       var myvalue=MainData.Rows.Find(mymatch.ID)[targetkey];
                       if (myvalue.ToString() == "")
                       {
                           MainData.Rows.Find(mymatch.ID)[targetkey] = mymatch.IID;
                       }
                       else
                       {
                           if (myvalue.ToString() != mymatch.IID.ToString())
                           {
                               errolist.Add(new EntityMatchErroModel() { ID = Convert.ToInt32(mymatch.ID), Rule = string.Join("+", group), IID = mymatch.IID, Key = mymatch.Key });
                           }
                       }
                   }
                   MainData.Columns.Remove("MatchValue");
               }
           }
       }

       private DataTable  GetEntityTargetRuleTable(DataTable MainData, EntityModel entity, EntityIndentityGroup group,string conn)
       {
           DataTable result = new DataTable();
           string str_group = "";
           string str_column = "";
           var pkstr = new Littlebeer.MDM.MSO.TableManager(conn).GetIdendtityColumn(entity.EntityName);
           if (group.Count > 0)
           {
               str_group = "[" + string.Join("]+[", group) + "]";
           }
           str_column = "IID=" + pkstr + ",MatchValue=" + str_group;

           string sql = string.Format("select {0} from {1}", str_column, entity.EntityName);
           SqlConnection cn = new SqlConnection(conn);
           SqlDataAdapter da = new SqlDataAdapter(sql, cn);
           DataSet ds = new DataSet();
           da.Fill(result);
           return result;
       }
     
    
   
   }
}
